package com.atguigu.springcloudalibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * ribbon 测试 springcloudAlibaba  服务熔断
 * 9003 9004
 */
@RestController
public class CircleBreakerController {
    @Value("${service-url.nacos-user-service}")
    private String providerUrl;

    @Resource
    private RestTemplate restTemplate;

    @GetMapping(value = "/consumer/fallback/{id}")
//    @SentinelResource(value = "fallback")//没有设置
    @SentinelResource(value = "fallback",fallback = "handlerFallback")//只负责业务异常
    public CommonResult fallback(@PathVariable("id")Long id){
        CommonResult result = restTemplate.getForObject(providerUrl+"/paymentSql/"+id,CommonResult.class,id);

        if (id ==4){
            throw  new IllegalArgumentException("IllegalAccessException 非法参数");
        }else if (result == null){
            throw new NullPointerException("NullPointerExceptionV 没有对应的记录  空指针异常");
        }
        return  result;
    }

    public CommonResult handlerFallback(@PathVariable Long id,Throwable e){
        Payment payment = new Payment(id,"null");
        return new CommonResult(4444,"兜底异常handlerFallback，异常内容"+e.getMessage(),payment);
    }
}
